package com.bingxue.edu.framework.mybatis;

import cn.hutool.core.util.ObjUtil;
import com.bingxue.edu.framework.common.model.AuditableEntity;
import com.bingxue.edu.framework.mybatis.listener.AuditingInsertListener;
import com.bingxue.edu.framework.mybatis.listener.AuditingUpdateListener;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector;
import com.mybatisflex.core.keygen.KeyGenerators;
import com.mybatisflex.core.query.QueryColumnBehavior;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author panbo
 * @since 2024/6/28
 */
@Configuration(proxyBeanMethods = false)
//@AutoConfiguration(before = MybatisFlexAutoConfiguration.class)
public class MybatisFlexAutoConfiguration implements MyBatisFlexCustomizer {

    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    static {
        QueryColumnBehavior.setSmartConvertInToEquals(true);
        QueryColumnBehavior.setIgnoreFunction(ObjUtil::isEmpty);
//        QueryColumnBehavior.setIgnoreFunction(QueryColumnBehavior.IGNORE_EMPTY);
    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        // 字段填充
        flexGlobalConfig.registerInsertListener(new AuditingInsertListener(), AuditableEntity.class);
        flexGlobalConfig.registerUpdateListener(new AuditingUpdateListener(), AuditableEntity.class);

        // 主键策略
        FlexGlobalConfig.KeyConfig keyConfig = new FlexGlobalConfig.KeyConfig();
        keyConfig.setKeyType(KeyType.Generator);
        keyConfig.setValue(KeyGenerators.flexId);
        flexGlobalConfig.setKeyConfig(keyConfig);

        // 打印sql
        if (!activeProfile.contains("prod")) {
            AuditManager.setAuditEnable(true);
            MessageCollector collector = new ConsoleMessageCollector();
            AuditManager.setMessageCollector(collector);
        }
    }
}
